package com.example.ffepeg.ffeImg;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;

public class TestThreadSema {
    // 创建一个BlockingQueue实例
    private final BlockingQueue<String> queue = new LinkedBlockingQueue<>();
    private final Semaphore semaphore = new Semaphore(1); // 控制并发数量

    public TestThreadSema() {
        // 启动处理线程
        Thread processorThread = new Thread(() -> {
            try {
                while (true) {
                    // 从队列中取数据，如果队列为空则等待
                    String data = queue.take();
                    semaphore.acquire(); // 获取许可
                    processData(data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
                System.out.println("Processor thread was interrupted.");
            }
        });
        processorThread.start();
    }

    // 处理数据的方法
    private void processData(final String data) {
        new Thread(() -> {
            try {
                System.out.println("Processing: " + data);
            } finally {
                semaphore.release(); // 确保许可被释放
            }
        }).start();
    }

    // 添加数据到队列的方法
    public void addDataToQueue(String data) throws InterruptedException {
        queue.put(data);
    }

    public static void main(String[] args) throws InterruptedException {
        TestThreadSema processor = new TestThreadSema();

        // 假设这是在其他地方产生并添加到队列的数据
        processor.addDataToQueue("data1");
        processor.addDataToQueue("data2");
    }

}
